package com.pay.ioopos.fragment;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Switch;

import androidx.fragment.app.Fragment;

import com.pay.ioopos.DataFactory;
import com.pay.ioopos.DataStore;
import com.pay.ioopos.KeyCodeFactory;
import com.pay.ioopos.KeyInfo;
import com.pay.ioopos.R;

import java.util.ArrayList;
import java.util.List;

import static com.pay.ioopos.KeyInfo.KEY_ENTER;


public class FunctionSwitchFragment extends Fragment implements View.OnKeyListener {

    private List<Switch> list;
    private DataStore store;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_function_switch, container, false);
        store = DataFactory.getDataStore();
        list = new ArrayList<>();

        Switch scanPay = view.findViewById(R.id.switch_scan_pay);
        scanPay.setOnKeyListener(this);
        scanPay.setChecked(store.getSwitchScanPay());
        list.add(scanPay);

        Switch icPay = view.findViewById(R.id.switch_ic_pay);
        icPay.setOnKeyListener(this);
        icPay.setChecked(store.getSwitchIcPay());
        list.add(icPay);

        Switch scanRefund = view.findViewById(R.id.switch_scan_refund);
        scanRefund.setOnKeyListener(this);
        scanRefund.setChecked(store.getSwitchScanRefund());
        list.add(scanRefund);

        scanPay.requestFocus();

        return view;

    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        KeyInfo keyInfo = KeyCodeFactory.getKeyInfo(keyCode);
        if (null == keyInfo) {
            return false;
        }
        if (event.getAction() != KeyEvent.ACTION_DOWN) {
            return false;
        }

        switch (keyInfo) {
            case KEY_NUM_1:
            case KEY_NUM_2:
            case KEY_NUM_3:
                Switch item = list.get(Integer.parseInt(keyInfo.getValue()) - 1);
                item.requestFocus();
                item.setChecked(!item.isChecked());
                store.set(String.valueOf(item.getText()), String.valueOf(item.isChecked()));
                return true;
        }
        if (keyInfo == KEY_ENTER) {
            list.forEach(item -> item.setKeyListener(null));
        }

        return false;
    }
}
